//
//  TZImageTool.m
//  
//  jhf
//
//  Created by 计海峰 on 2017/6/20.
//  Copyright © 2017年 计海峰. All rights reserved.
//

#import "TZImageTool.h"
#import "TZImageManager.h"
#import <RSKImageCropper/RSKImageCropViewController.h>

@interface TZImageTool() // <RSKImageCropViewControllerDelegate>

@property (nonatomic, strong) UIImage *currImg;

@property (nonatomic, copy) BlockValue block;

@end

@implementation TZImageTool

JSingletonM();

//#pragma make RSKImageCropViewControllerDelegate delegate
//- (void)imageCropViewController:(RSKImageCropViewController *)controller didCropImage:(UIImage *)croppedImage usingCropRect:(CGRect)cropRect rotationAngle:(CGFloat)rotationAngle{
//    [controller dismissViewControllerAnimated:YES completion:nil];
//    if (self.block) {
//        self.block(-1, croppedImage);
//    }
//}
//
//- (void)imageCropViewControllerDidCancelCrop:(RSKImageCropViewController *)controller{
//    [controller dismissViewControllerAnimated:YES completion:nil];
//}

+ (UIViewController *)currentTarget:(UIViewController *)target {
    if (!target) {
        UIWindow * window = [[UIApplication sharedApplication] keyWindow];
        target = [window currentTopViewController];
    }else if ([target isKindOfClass:UIViewController.class]) {
        return target;
    }else if ([target isKindOfClass:UIView.class]) {
        return [JUtil findViewController:(UIView *)target];
    }
    return [[[UIApplication sharedApplication] keyWindow] currentTopViewController];
}

/**
 获得单张图片
 
 @param clipping 是否剪辑
 @param target 某个controller
 @param block 回调
 */
- (void)addSinglePhotoWithClipping:(BOOL)clipping andTarget:(UIViewController *)target andBLock:(BlockValue)block;{
    target = [TZImageTool currentTarget:target];
    //
    [TZImageTool shared].block = block;
    TZImagePickerController *imagePickerVC = [TZImageTool imagePickerVC];
    imagePickerVC.allowPickingGif = false;
    imagePickerVC.maxImagesCount = 1;
    imagePickerVC.showSelectBtn = false;
    if (clipping) {
        imagePickerVC.allowPickingOriginalPhoto = false;
        imagePickerVC.isSelectOriginalPhoto = false;
        imagePickerVC.allowCrop = true;
        imagePickerVC.needCircleCrop = false;
    }
    [imagePickerVC.selectedAssets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [imagePickerVC removeSelectedModel:obj];
    }];
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (clipping) {
            if (block) {
                block(-1,photos.firstObject);
            }
            //            RSKImageCropViewController *imageCropVC = [[RSKImageCropViewController alloc] initWithImage:photos.firstObject];
            //            imageCropVC.delegate = [TZImageTool shared];
            //            [target presentViewController:imageCropVC animated:YES completion:nil];
        }else{
            if (block) {
                block(-1,photos.firstObject);
            }
        }
    }];
    [target presentViewController:imagePickerVC animated:YES completion:nil];
}

/**
 获得单张图片
 
 @param radio 剪裁比例
 @param target 某个controller
 @param block 回调
 */
- (void)addSinglePhotoClippingRadio:(CGFloat)radio andTarget:(UIViewController *)target andBLock:(BlockValue)block;{
    target = [TZImageTool currentTarget:target];
    //
    [TZImageTool shared].block = block;
    TZImagePickerController *imagePickerVC = [TZImageTool imagePickerVC];
    imagePickerVC.allowPickingGif = false;
    imagePickerVC.maxImagesCount = 1;
    imagePickerVC.showSelectBtn = false;
    
    imagePickerVC.allowPickingOriginalPhoto = false;
    imagePickerVC.isSelectOriginalPhoto = false;
    imagePickerVC.allowCrop = true;
    imagePickerVC.needCircleCrop = false;
    
    CGFloat height = (kScreen_Width - 20) * radio;
    imagePickerVC.cropRect = CGRectMake(10, (kScreen_Height - height)/2.0, kScreen_Width - 20, height);
     
    [imagePickerVC.selectedAssets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [imagePickerVC removeSelectedModel:obj];
    }];
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (block) {
            block(-1, photos.firstObject);
        }
    }];
    [target presentViewController:imagePickerVC animated:YES completion:nil];
}

/**
 添加多个图片

 @param maxNum 图片最大数量
 @param selectedAssets 已经选过的
 @param target 某个controller
 @param block 回调
 */
+ (void)addPhotosMaxNum:(NSInteger)maxNum selectedAssets:(NSMutableArray *)selectedAssets andTarget:(UIViewController *)target andBlock:(void (^)(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto))block; {
    target = [TZImageTool currentTarget:target];
    //
    TZImagePickerController *imagePickerVC = [TZImageTool imagePickerVC];
    imagePickerVC.maxImagesCount = maxNum;
    if (selectedAssets && selectedAssets.count > 0) { // 1.设置目前已经选中的图片数组
        imagePickerVC.selectedAssets = selectedAssets;
    }else {
        imagePickerVC.selectedAssets = [NSMutableArray array];
    }
    [imagePickerVC.selectedAssets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [imagePickerVC removeSelectedModel:obj];
    }];
    [imagePickerVC setDidFinishPickingPhotosHandle:block];
    [target presentViewController:imagePickerVC animated:YES completion:nil];
}

/**
 添加视频或者图片

 @param maxNum 最大数量
 @param selectedAssets 已经选过的
 @param target 某个controller
 @param videoQuality 视频品质 默认 AVAssetExportPresetLowQuality
 @param imageBlock imageBlock
 @param videoBlock videoBlock
 */
+ (void)addPhotosOrSingleVideoMaxNum:(NSInteger)maxNum selectedAssets:(NSMutableArray *)selectedAssets andTarget:(UIViewController *)target videoQuality:(NSString *)videoQuality andBlock:(void (^)(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto))imageBlock andSingleVideo:(void(^)(UIImage *coverImage, id asset))videoBlock {
    target = [TZImageTool currentTarget:target];
    //
    TZImagePickerController *imagePickerVC = [TZImageTool imagePickerVC];
    imagePickerVC.maxImagesCount = maxNum;
    if (selectedAssets && selectedAssets.count > 0) { // 1.设置目前已经选中的图片数组
        imagePickerVC.selectedAssets = selectedAssets;
    }else {
        imagePickerVC.selectedAssets = [NSMutableArray array];
    }
    imagePickerVC.allowPickingVideo = YES;
    [imagePickerVC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (imageBlock) {
            imageBlock(photos, assets, isSelectOriginalPhoto);
        }
    }];
    
    [imagePickerVC setDidFinishPickingVideoHandle:^(UIImage *coverImage, id asset) {
        [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetLowQuality success:^(NSString *outputPath) {
            if (videoBlock) {
                videoBlock(coverImage, outputPath);
            }
        } failure:^(NSString *errorMessage, NSError *error) {
            NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
        }];
    }];
    [target presentViewController:imagePickerVC animated:YES completion:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        imagePickerVC.allowPickingVideo = false;
    });
}


/// 获取视频
/// @param target 某个controller
/// @param videoQuality 视频品质 默认 AVAssetExportPresetLowQuality
/// @param videoBlock videoBlock
+ (void)addSingleVideoWithTarget:(UIViewController *)target videoQuality:(NSString *)videoQuality videoBlock:(void (^)(UIImage *coverImage, id asset))videoBlock {
    target = [TZImageTool currentTarget:target];
    //
    TZImagePickerController *imagePickerVC = [TZImageTool imagePickerVC];
    imagePickerVC.maxImagesCount = 1;
    imagePickerVC.showSelectBtn = false;
    imagePickerVC.allowPickingVideo = false;
    imagePickerVC.allowPickingImage = false;
    imagePickerVC.allowPickingOriginalPhoto = false;
    imagePickerVC.allowPickingGif = false;
    imagePickerVC.allowPickingVideo = true;
    imagePickerVC.selectedAssets = [NSMutableArray array];
    imagePickerVC.allowPickingMultipleVideo = true;
    imagePickerVC.didFinishPickingVideoHandle = ^(UIImage *coverImage, id asset) {
        [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:videoQuality ?: AVAssetExportPresetLowQuality success:^(NSString *outputPath) {
            if (videoBlock) {
                videoBlock(coverImage, outputPath);
            }
        } failure:^(NSString *errorMessage, NSError *error) {
            NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
        }];
    };
//    imagePickerVC.didFinishPickingPhotosWithInfosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
//
//    };
    [target presentViewController:imagePickerVC animated:YES completion:nil];
}

/// 获取视频
/// @param target 某个controller
/// @param maxCount 最多获取几个
/// @param videoBlock videoBlock
+ (void)addVideosWithTarget:(UIViewController *)target maxCount:(NSInteger)maxCount videoBlock:(void (^)(NSArray<UIImage *> *coverImage, NSArray *assets, NSArray<NSDictionary *> *infos))videoBlock {
    target = [TZImageTool currentTarget:target];
    //
    TZImagePickerController *imagePickerVC = [TZImageTool imagePickerVC];
    imagePickerVC.maxImagesCount = maxCount;
    imagePickerVC.showSelectBtn = false;
    imagePickerVC.allowPickingVideo = false;
    imagePickerVC.allowPickingImage = false;
    imagePickerVC.allowPickingOriginalPhoto = false;
    imagePickerVC.allowPickingGif = false;
    imagePickerVC.allowPickingVideo = true;
    imagePickerVC.selectedAssets = [NSMutableArray array];
    imagePickerVC.allowPickingMultipleVideo = true;
    imagePickerVC.didFinishPickingVideoHandle = ^(UIImage *coverImage, id asset) {
        if (videoBlock) {
            videoBlock(@[coverImage], @[asset], nil);
        }
    };
    imagePickerVC.didFinishPickingPhotosWithInfosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
        if (videoBlock) {
            videoBlock(photos, assets, infos);
        }
    };
    [target presentViewController:imagePickerVC animated:YES completion:nil];
}

/// 导出视频
/// @param asset 获取视频的PHAsset
/// @param videoBlock videoBlock
/// @param failure failure
+ (void)convertPHAssetToViedo:(id)asset videoBlock:(void (^)(id path))videoBlock failure:(void (^)(NSString *errorMessage, NSError *error))failure {
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetLowQuality success:^(NSString *outputPath) {
        if (videoBlock) {
            videoBlock(outputPath);
        }
    } failure:^(NSString *errorMessage, NSError *error) {
        NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
        if (failure) {
            failure(errorMessage, error);
        }
    }];
}

//MARK: - 初始化选择器
+ (TZImagePickerController *)imagePickerVC {
    TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:9 columnNumber:4 delegate:nil pushPhotoPickerVc:YES];
    picker.isSelectOriginalPhoto = YES;
    picker.statusBarStyle = UIStatusBarStyleLightContent;
    picker.allowTakePicture = YES;
    
    // imagePickerVC.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVC.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVC.oKButtonTitleColorNormal = [UIColor greenColor];
    // imagePickerVC.navigationBar.translucent = NO;
    
    picker.allowPickingVideo = false;
    picker.allowPickingImage = true;
    picker.allowPickingOriginalPhoto = true;
    picker.allowPickingGif = true;
    
    // 对照片排序，按修改时间升序，默认是YES。如果设置为NO,最新的照片会显示在最前面，内部的拍照按钮会排在第一个
    picker.sortAscendingByModificationDate = true;
    
    picker.showSelectBtn = YES;
    return picker;
}



@end
